package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.dto.UpdateByQueryDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessTypeErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasSpecialParamPojo;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.invoice.pojo.dto.InvoiceAmountDetailDTO;
import com.xbongbong.pro.purchaseinvoice.dto.InvoiceAmountHandleDTO;
import com.xbongbong.pro.purchaseinvoice.dto.PurchaseInvoiceAmountDetailGetDTO;
import com.xbongbong.pro.purchaseinvoice.vo.PurchaseInvoiceAmountDetailVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.InvoiceConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.PurchaseInvoiceDao;
import com.xbongbong.saas.domain.entity.PurchaseInvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.PayPlanSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseInvoiceEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.help.AddMapHelp;
import com.xbongbong.saas.help.InvoiceCommonHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PurchaseInvoiceModel;
import com.xbongbong.saas.model.PurchaseInvoiceRelationshipModel;
import com.xbongbong.saas.model.PurchaseInvoiceSubDataModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @author yuqian
 * @version v1.0
 * @date 2020/2/17 17:23
 * @since v1.0
 */
@Service("purchaseInvoiceModel")
public class PurchaseInvoiceModelImpl implements PurchaseInvoiceModel {

    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PurchaseInvoiceDao purchaseInvoiceDao;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private PurchaseInvoiceSubDataModel purchaseInvoiceSubDataModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private PurchaseInvoiceModel purchaseInvoiceModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private PurchaseInvoiceRelationshipModel purchaseInvoiceRelationshipModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private PayPlanSheetModel paySheetModel;

    @Override
    public Integer save(PurchaseInvoiceEntityExt invoiceEntity) throws XbbException {
        return null;
    }

    @Override
    public PurchaseInvoiceEntityExt getByKey(Long key, String corpid) {
        PurchaseInvoiceEntityExt purchaseInvoiceEntityExt = purchaseInvoiceDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(purchaseInvoiceEntityExt), IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(purchaseInvoiceEntityExt), IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB);
        return purchaseInvoiceEntityExt;
    }


    @Override
    public Integer updateBatchByRule(List<Map<String, Object>> valueList, List<Long> idsList, String corpid) throws XbbException {
        // TODO: 2020/9/22
        StandardizeDataUtil.standardizeListMap(valueList);
        Integer update = purchaseInvoiceDao.updateBatchByRule(valueList, idsList, corpid);
        UpdateByQueryDTO updateByQueryDTO = new UpdateByQueryDTO();
        updateByQueryDTO.setIdList(idsList);
        updateByQueryDTO.setCorpid(corpid);
        Map<String, Object> updateDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        valueList.forEach((item)->{
            updateDataMap.put("data."+item.get("attr"), item.get("value"));
        });
        updateByQueryDTO.setUpdateDataMap(updateDataMap);
        updateByQueryDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE);
        return update;
    }

    @Override
    public Integer deleteBatch(List<Long> idIn, String corpid) throws XbbException {
        paasEsModel.deleteBatch(idIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE);
        Integer integer = purchaseInvoiceDao.deleteBatch(idIn, corpid);
        paasFormSubDataModel.deleteBatchByDataId(idIn, corpid, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS, DelEnum.DELETE_SUBFORM);
        paasFormSubDataModel.deleteBatchByDataId(idIn, corpid, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteByKey(Long id, String corpid) throws XbbException {
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+id);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE);
        paasEsModel.delete(deleteDTO);
        Integer integer = purchaseInvoiceDao.deleteByKey(id, corpid);
        paasFormSubDataModel.deleteByDataId(id, corpid, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
        paasFormSubDataModel.deleteByDataId(id, corpid, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB);
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = purchaseInvoiceDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE);
        }
        if (!subList.isEmpty()) {
            purchaseInvoiceSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = purchaseInvoiceDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            purchaseInvoiceSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, boolean needThrow) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = purchaseInvoiceDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE,needThrow);
        }
        if (!subList.isEmpty()) {
            purchaseInvoiceSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer insert(PurchaseInvoiceEntityExt entity) throws XbbException {
        //TODO  先进行数据库的插入动作
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSingleSubForm(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = purchaseInvoiceDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSingleSubFormData(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB);
        return success;
    }

    @Override
    public Integer update(PurchaseInvoiceEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSingleSubForm(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = purchaseInvoiceDao.update(entity);
        Integer updateSingleSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSingleSub) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = purchaseInvoiceDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE);
            paasEsModel.update(insertDTO);


        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        if (Objects.nonNull(entity.getSingleSubFormData()) && !entity.getSingleSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSingleSubFormData());
        }
        return success;
    }

    @Override
    public List<PurchaseInvoiceEntityExt> findEntitys(Map<String, Object> param) {
        List<PurchaseInvoiceEntityExt> entitys = purchaseInvoiceDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return purchaseInvoiceDao.getEntitysCount(param);
    }

    @Override
    public List<PurchaseInvoiceEntityExt> getEntityByPurchaseIdOrRefId(Map<String,Object> param){
        List<PurchaseInvoiceEntityExt> purchaseInvoiceEntityExts = purchaseInvoiceDao.getEntityByPurchaseIdOrRefId(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), purchaseInvoiceEntityExts, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
            paasFormSubDataModel.findSubEntity(corpid.toString(), purchaseInvoiceEntityExts, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB);
        }
        return purchaseInvoiceEntityExts;
    }

    @Override
    public List<PurchaseInvoiceEntityExt> getRedPurchaseInvoice(Map<String,Object> param) {
        List<PurchaseInvoiceEntityExt> purchaseInvoiceEntityExts = purchaseInvoiceDao.getRedPurchaseInvoice(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), purchaseInvoiceEntityExts, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
            paasFormSubDataModel.findSubEntity(corpid.toString(), purchaseInvoiceEntityExts, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_SUB);
        }
        return purchaseInvoiceEntityExts;
    }

    @Override
    public Integer restoreBatch(List<Long> dataIdList, String corpid, Integer del) throws XbbException {
        return null;
    }

    @Override
    public List<PurchaseInvoiceEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return purchaseInvoiceDao.findEntitys(param);
    }

    @Override
    public Double getRedTotalMoney(Long originId, String corpid) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.FLOW_STATUS_IN, Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType()));
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.PURCHASE_INVOICE.getCode(), PurchaseInvoiceEnum.ORIGIN_ID.getAttr(), originId, param, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE);
        Double redTotalMoney = 0D;
        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
            Double money = getDoubleFromFormData(paasFormDataEntityExt.getData(),PurchaseInvoiceEnum.TOTAL_MONEY.getAttr());
            if (money == null) {
                money = 0D;
            }
            redTotalMoney += money;
        }
        return redTotalMoney;
    }

    /**
     * 编辑时改变解释
     *
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     */
    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        SaasSpecialParamPojo saasSpecialParamPojo = formatExplainDTO.getSaasSpecialParamPojo();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr())) {
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
            }
        }
        if (saasSpecialParamPojo != null && Objects.equals(saasSpecialParamPojo.getFromRed(), BasicConstant.ONE)) {
            PaasFormDataEntityExt dataEntity = formatExplainDTO.getDataEntity();
            JSONObject dataList = formatExplainDTO.getResult();
            Long id = dataEntity.getId();
            String esData = StringConstant.JSON_DATA + StringConstant.POINT;
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(esData + PurchaseInvoiceEnum.ORIGIN_ID.getAttr(), id));
            boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD , formatExplainDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE.getType()));
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE.getIndex());
            searchRequest.source(sourceBuilder);
            Long count = xbbElasticsearchRestTemplate.count(searchRequest, PaasFormDataEntityExt.class);
            String sheetNo = dataEntity.getSerialNo();
            if (count == null) {
                count = 0L;
            }
            dataEntity.setSerialNo(sheetNo + StringConstant.POINT + (count.intValue() + 1));
            Double totalMoney = getDoubleOrDefaultFromFormData(dataList, PurchaseInvoiceEnum.TOTAL_MONEY.getAttr(), 0D);
            Double redTotalMoney = getRedTotalMoney(id, formatExplainDTO.getCorpid());
            JSONArray originArr = new JSONArray();
            JSONObject originObj = new JSONObject();
            originObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, id);
            originObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, sheetNo);
            originArr.add(originObj);
            dataList.put(PurchaseInvoiceEnum.ORIGIN_ID.getAttr(), originArr);
            //进项发票 显示是 正的
            dataList.put(PurchaseInvoiceEnum.TOTAL_MONEY.getAttr(), totalMoney + redTotalMoney);
            dataList.put(PurchaseInvoiceEnum.INVOICE_DATE.getAttr(), DateTimeUtil.getInt());
            for (FieldAttrEntity fieldAttrEntity : explainList) {
                if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInvoiceEnum.ORIGIN_ID.getAttr())) {
                    fieldAttrEntity.setShowType(ShowTypeEnum.EDIT.getCode());
                    fieldAttrEntity.setEditable(BasicConstant.ZERO);
                }
                if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInvoiceEnum.TOTAL_MONEY.getAttr())) {
                    fieldAttrEntity.setAttrName("红冲发票金额");
                }
                if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr())) {
                    fieldAttrEntity.setEditable(BasicConstant.ZERO);
                }
                if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInvoiceEnum.PURCHASE_ID.getAttr())) {
                    fieldAttrEntity.setEditable(BasicConstant.ZERO);
                }
                if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr())) {
                    fieldAttrEntity.setEditable(BasicConstant.ZERO);
                }
            }
        }
    }

    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr(), PurchaseInvoiceEnum.SUPPLIER_NAME_LINK_TEXT.getAttr(), PurchaseInvoiceEnum.SUPPLIER_NAME.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, PurchaseInvoiceEnum.PURCHASE_ID.getAttr(), PurchaseInvoiceEnum.PURCHASE_ID_LINK_TEXT.getAttr(), PurchaseInvoiceEnum.PURCHASE_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr(), PurchaseInvoiceEnum.PAY_PLAN_ID_LINK_TEXT.getAttr(), PurchaseInvoiceEnum.PAY_PLAN_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, PurchaseInvoiceEnum.PAY_SHEET_ID.getAttr(), PurchaseInvoiceEnum.PAY_SHEET_ID_LINK_TEXT.getAttr(), PurchaseInvoiceEnum.PAY_SHEET_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, PurchaseInvoiceEnum.ORIGIN_ID.getAttr(), PurchaseInvoiceEnum.ORIGIN_ID_LINK_TEXT.getAttr(), PurchaseInvoiceEnum.ORIGIN_ID.getFieldType());
    }

    @Override
    public PurchaseInvoiceAmountDetailVO getPurchaseInvoiceAmountDetail(PurchaseInvoiceAmountDetailGetDTO purchaseInvoiceAmountDetailGetDTO) throws XbbException{
        if(!Objects.equals(purchaseInvoiceAmountDetailGetDTO.getBusinessType(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
            throw new XbbException(BusinessTypeErrorCodeEnum.API_ERROR_361001);
        }
        //如果是从获取金额明细接口过来
        if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsGetDetail(),BasicConstant.ONE) && Objects.nonNull(purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId())){
            purchaseInvoiceAmountDetailGetDTO.setIsEdit(BasicConstant.ONE);
        }
        //红冲编辑需要知道原发票id
        List<Long> redIdAndOrigialList = new ArrayList<>();
        Long originId = 0L;
        boolean redFlag = (Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsRed(),BasicConstant.ONE) && Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE)) || Objects.equals(purchaseInvoiceAmountDetailGetDTO.getFormRed(),BasicConstant.ONE);
        //红冲编辑时
        if(Objects.nonNull(purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId()) && Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsRed(),BasicConstant.ONE) && Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE)){
            PurchaseInvoiceEntityExt purchaseInvoiceEntityExt = purchaseInvoiceModel.getByKey(purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId(),purchaseInvoiceAmountDetailGetDTO.getCorpid());
            if(Objects.nonNull(purchaseInvoiceEntityExt)){
                purchaseInvoiceAmountDetailGetDTO.setIsEdit(BasicConstant.ONE);
                JSONObject data = purchaseInvoiceEntityExt.getData();
                originId = data.getLong(PurchaseInvoiceEnum.ORIGIN_ID.getAttr());
                redIdAndOrigialList.add(originId);
            }
        }

        if(Objects.nonNull(purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId())){
            redIdAndOrigialList.add(purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId());
        }
        //红冲的时候直接去找所有红冲 红冲编辑时去找被红冲的这个发票下面的所有红冲
        if(redFlag){
            if(Objects.nonNull(purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId()) && purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId() > 0L) {
                String esData = StringConstant.JSON_DATA + StringConstant.POINT;
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsRed(),BasicConstant.ONE) && Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE)) {
                    boolQueryBuilder.filter(termQuery(esData + PurchaseInvoiceEnum.ORIGIN_ID.getAttr(), originId));
                }else {
                    boolQueryBuilder.filter(termQuery(esData + PurchaseInvoiceEnum.ORIGIN_ID.getAttr(), purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId()));
                }
                boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, purchaseInvoiceAmountDetailGetDTO.getCorpid()));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.DATA_ID);
                //查询出这个发票下面的所有红冲
                List<PaasFormDataEntityExt> redPurchaseInvoiceList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
                if(CollectionsUtil.isNotEmpty(redPurchaseInvoiceList)){
                    for(PaasFormDataEntityExt paasFormDataEntityExt : redPurchaseInvoiceList){
                        redIdAndOrigialList.add(paasFormDataEntityExt.getDataId());
                    }
                }
            }
        }
        List<InvoiceAmountDetailDTO> amountDetail = new ArrayList<>();
        Map<Long,Double> purchaseInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> payPlanInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,Double> paySheetInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        InvoiceAmountHandleDTO invoiceAmountHandleDTO = new InvoiceAmountHandleDTO();
        List<JSONObject> userList = new ArrayList<>();
        if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsGetDetail(),BasicConstant.ONE)){
            invoiceAmountHandleDTO.setIsGetDetail(BasicConstant.ONE);
        }
        //第一部查询供应商
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",purchaseInvoiceAmountDetailGetDTO.getCorpid());
        param.put("del",DelEnum.NORMAL.getDel());
        param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getSupplierIdList());
        List<SupplierEntityExt> supplierEntityExts = supplierModel.findEntitys(param);
        if(CollectionsUtil.isNotEmpty(supplierEntityExts)) {
            for(SupplierEntityExt supplierEntityExt : supplierEntityExts) {
                JSONObject data = supplierEntityExt.getData();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(BasicConstant.ID,supplierEntityExt.getId());
                jsonObject.put(BasicConstant.NAME, FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierEnum.SUPPLIER_NAME.getAttr(),""));
                userList.add(jsonObject);
            }
            invoiceAmountHandleDTO.setSuppplierList(userList);
        }
        //第二步查询采购合同 和 合同的开票 记录
        if(CollectionsUtil.isNotEmpty(purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList())) {
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList());
            List<PurchaseEntityExt> purchaseEntityExts = purchaseModel.findEntitys(param);
            purchaseEntityExts = InvoiceCommonHelp.sortEntityById(purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList(), purchaseEntityExts,PurchaseEntityExt.class);
            invoiceAmountHandleDTO.setPurchaseEntityExts(purchaseEntityExts);
            param.remove("idIn");
            param.put("purchaseIdIn", purchaseInvoiceAmountDetailGetDTO.getPurchaseIdList());
            if (Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(), BasicConstant.ONE)) {
                param.put("purchaseInvoiceIdNot", purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId());
            }else if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getFormRed(),BasicConstant.ONE)){
                if(redIdAndOrigialList.size() > BasicConstant.ZERO) {
                    param.put("purchaseInvoiceIdIn", redIdAndOrigialList);
                }
            }
            param.put("isCancel",BasicConstant.ZERO);
            List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
            if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntities)) {
                for (PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities) {
                    if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsRed(),BasicConstant.ONE) && Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE)){
                        if(!redIdAndOrigialList.contains(purchaseInvoiceRelationshipEntity.getPurchaseInvoiceId())){
                            continue;
                        }
                    }
                    AddMapHelp.addMapNormal(purchaseInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPurchaseId(),purchaseInvoiceRelationshipEntity.getMoney());
                }
                invoiceAmountHandleDTO.setPurchaseInvoiceAmountMap(purchaseInvoiceAmountMap);
            }
        }
        //第三步查询付款单 付款计划
        if(CollectionsUtil.isNotEmpty(purchaseInvoiceAmountDetailGetDTO.getPayPlanIdList())){
            param.clear();
            param.put("corpid",purchaseInvoiceAmountDetailGetDTO.getCorpid());
            param.put("del",DelEnum.NORMAL.getDel());
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getPayPlanIdList());
            List<PayPlanEntityExt> payPlanEntityExts = payPlanModel.findEntitys(param);
            payPlanEntityExts = InvoiceCommonHelp.sortEntityById(purchaseInvoiceAmountDetailGetDTO.getPayPlanIdList(), payPlanEntityExts,PayPlanEntityExt.class);
            invoiceAmountHandleDTO.setPayPlanEntityExts(payPlanEntityExts);
            param.remove("idIn");
            param.put("payPlanIdIn", purchaseInvoiceAmountDetailGetDTO.getPayPlanIdList());
            if (Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(), BasicConstant.ONE)) {
                param.put("purchaseInvoiceIdNot", purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId());
            } else if (Objects.equals(purchaseInvoiceAmountDetailGetDTO.getFormRed(), BasicConstant.ONE)) {
                if (redIdAndOrigialList.size() > BasicConstant.ZERO) {
                    param.put("purchaseInvoiceIdIn", redIdAndOrigialList);
                }
            }
            param.put("isCancel", BasicConstant.ZERO);
            List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
            if (CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntities)) {
                for (PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities) {
                    if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsRed(),BasicConstant.ONE) && Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE)){
                        if(!redIdAndOrigialList.contains(purchaseInvoiceRelationshipEntity.getPurchaseInvoiceId())){
                            continue;
                        }
                    }
                    AddMapHelp.addMapNormal(payPlanInvoiceAmountMap, purchaseInvoiceRelationshipEntity.getPayPlanId(), purchaseInvoiceRelationshipEntity.getMoney());
                }
                invoiceAmountHandleDTO.setPayPlanInvoiceAmountMap(payPlanInvoiceAmountMap);
            }

        }
        if(CollectionsUtil.isNotEmpty(purchaseInvoiceAmountDetailGetDTO.getPaySheetIdList())){
            param.clear();
            param.put("corpid",purchaseInvoiceAmountDetailGetDTO.getCorpid());
            param.put("del",DelEnum.NORMAL.getDel());
            param.put("idIn",purchaseInvoiceAmountDetailGetDTO.getPaySheetIdList());
            List<PayPlanSheetEntityExt> payPlanSheetEntityExts = paySheetModel.findEntitys(param);
            payPlanSheetEntityExts = InvoiceCommonHelp.sortEntityById(purchaseInvoiceAmountDetailGetDTO.getPaySheetIdList(), payPlanSheetEntityExts,PayPlanSheetEntityExt.class);
            invoiceAmountHandleDTO.setPaySheetEntityExtS(payPlanSheetEntityExts);
            param.remove("idIn");
            param.put("paySheetIdIn", purchaseInvoiceAmountDetailGetDTO.getPaySheetIdList());
            if (Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(), BasicConstant.ONE)) {
                param.put("purchaseInvoiceIdNot", purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId());
            } else if (Objects.equals(purchaseInvoiceAmountDetailGetDTO.getFormRed(), BasicConstant.ONE)) {
                if (redIdAndOrigialList.size() > BasicConstant.ZERO) {
                    param.put("purchaseInvoiceIdIn", redIdAndOrigialList);
                }
            }
            param.put("isCancel", BasicConstant.ZERO);
            List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
            if (CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntities)) {
                for (PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities) {
                    if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsRed(),BasicConstant.ONE) && Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE)){
                        if(!redIdAndOrigialList.contains(purchaseInvoiceRelationshipEntity.getPurchaseInvoiceId())){
                            continue;
                        }
                    }
                    AddMapHelp.addMapNormal(paySheetInvoiceAmountMap, purchaseInvoiceRelationshipEntity.getPaySheetId(), purchaseInvoiceRelationshipEntity.getMoney());
                }
                invoiceAmountHandleDTO.setPaySheetInvoiceAmountMap(paySheetInvoiceAmountMap);
            }
        }
        if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE)) {
            if (Objects.nonNull(purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId())) {
                Map<Long,Double> oldPurchaseInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long,Double> oldPayPlanInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long,Double> oldPaySheetInvoiceAmountMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("corpid", purchaseInvoiceAmountDetailGetDTO.getCorpid());
                map.put("del", DelEnum.NORMAL.getDel());
                map.put("purchaseInvoiceId", purchaseInvoiceAmountDetailGetDTO.getPurchaseInvoiceId());
                map.put("isCancel",BasicConstant.ZERO);
                List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(map);
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntities)){
                    for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities){
                        if(!Objects.equals(purchaseInvoiceRelationshipEntity.getPurchaseId(),0L)){
                            AddMapHelp.addMapNormal(oldPurchaseInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPurchaseId(),purchaseInvoiceRelationshipEntity.getMoney());
                        }
                        if(!Objects.equals(purchaseInvoiceRelationshipEntity.getPayPlanId(),0L)){
                            AddMapHelp.addMapNormal(oldPayPlanInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPayPlanId(),purchaseInvoiceRelationshipEntity.getMoney());
                        }
                        if(!Objects.equals(purchaseInvoiceRelationshipEntity.getPaySheetId(),0L)){
                            AddMapHelp.addMapNormal(oldPaySheetInvoiceAmountMap,purchaseInvoiceRelationshipEntity.getPaySheetId(),purchaseInvoiceRelationshipEntity.getMoney());
                        }
                    }
                    invoiceAmountHandleDTO.setOldPurchaseInvoiceAmountMap(oldPurchaseInvoiceAmountMap);
                    invoiceAmountHandleDTO.setOldPayPlanInvoiceAmountMap(oldPayPlanInvoiceAmountMap);
                    invoiceAmountHandleDTO.setOldPaySheetInvoiceAmountMap(oldPaySheetInvoiceAmountMap);
                    invoiceAmountHandleDTO.setIsEdit(purchaseInvoiceAmountDetailGetDTO.getIsEdit());
                }
            }
        }
        if(Objects.nonNull(purchaseInvoiceAmountDetailGetDTO.getIsRed())){
            invoiceAmountHandleDTO.setIsRed(purchaseInvoiceAmountDetailGetDTO.getIsRed());
        }
        if(Objects.nonNull(purchaseInvoiceAmountDetailGetDTO.getFormRed())){
            invoiceAmountHandleDTO.setIsRed(purchaseInvoiceAmountDetailGetDTO.getFormRed());
        }
        amountDetail = InvoiceCommonHelp.commonPackageAmountDetail2(invoiceAmountHandleDTO);
        PurchaseInvoiceAmountDetailVO purchaseInvoiceAmountDetailVO = new PurchaseInvoiceAmountDetailVO();
        purchaseInvoiceAmountDetailVO.setAmountDetail(amountDetail);
        return purchaseInvoiceAmountDetailVO;
    }

    /**
     * 审批获取金额明细
     * 思路: 走获取金额明细接口,但这个时候会丢失掉用户自己填写的开票金额,
     * 所以直接去saasNeedPojo 中去取然后在覆盖上去重新计算总开票金额
     * @param corpid
     * @param businessType
     * @param data
     * @param dataId
     * @param saasNeedPoJo
     * @return
     * @throws XbbException
     */
    @Override
    public JSONArray approveGetAmountDetail(String corpid, Integer businessType, JSONObject data, Long dataId, String saasNeedPoJo) throws XbbException{
        PurchaseInvoiceAmountDetailGetDTO purchaseInvoiceAmountDetailGetDTO = InvoiceCommonHelp.getAmountDetailByInvoiceData(dataId,data);
        purchaseInvoiceAmountDetailGetDTO.setCorpid(corpid);
        purchaseInvoiceAmountDetailGetDTO.setBusinessType(businessType);
        Long originId = FastJsonHelper.getLongOrDefaultFromFormData(data,PurchaseInvoiceEnum.ORIGIN_ID.getAttr(),0L);
        //红冲新建时
        boolean isAdd = Objects.isNull(dataId) || dataId == 0L;
        if(isAdd && originId >0L){
            purchaseInvoiceAmountDetailGetDTO.setFormRed(BasicConstant.ONE);
            purchaseInvoiceAmountDetailGetDTO.setPurchaseInvoiceId(originId);
        }
        //编辑时
        if(Objects.nonNull(dataId) && dataId >0L && originId <=0L){
            purchaseInvoiceAmountDetailGetDTO.setIsEdit(BasicConstant.ONE);
        }
        //红冲编辑
        if(Objects.nonNull(dataId) && dataId>0L && originId >0L){
            purchaseInvoiceAmountDetailGetDTO.setIsRed(BasicConstant.ONE);
            purchaseInvoiceAmountDetailGetDTO.setIsEdit(BasicConstant.ONE);
        }
        PurchaseInvoiceAmountDetailVO purchaseInvoiceAmountDetailVO = purchaseInvoiceModel.getPurchaseInvoiceAmountDetail(purchaseInvoiceAmountDetailGetDTO);
        JSONArray amountDetail = JSONArray.parseArray(JSONArray.toJSONString(purchaseInvoiceAmountDetailVO.getAmountDetail()));
        if(Objects.equals(purchaseInvoiceAmountDetailGetDTO.getFormRed(),BasicConstant.ONE) || (Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsRed(),BasicConstant.ONE) && Objects.equals(purchaseInvoiceAmountDetailGetDTO.getIsEdit(),BasicConstant.ONE))){
            InvoiceCommonHelp.getMinusAmountFormRedInvoice(data,amountDetail,originId,BasicConstant.ZERO,businessType);
        }
        //红冲编辑

        Map<Long,Double> invoiceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        JSONObject jsonObject = JSONObject.parseObject(saasNeedPoJo);
        JSONArray saasNeedPojoAmountDetail = jsonObject.getJSONArray(PaasConstant.AMOUNTDETAIL);
        if(CollectionsUtil.isNotEmpty(saasNeedPojoAmountDetail)) {
            for (int i = 0; i < saasNeedPojoAmountDetail.size(); i++) {
                JSONObject amountObj = saasNeedPojoAmountDetail.getJSONObject(i);
                if(Objects.nonNull(amountObj)) {
                    if (amountObj.containsKey(InvoiceConstant.INVOICE_AMOUNT)) {
                        if (CollectionsUtil.isNotEmpty(amountObj.getJSONArray(InvoiceConstant.PAYPLAN))) {
                            JSONObject payPlanObj = amountObj.getJSONArray(InvoiceConstant.PAYPLAN).getJSONObject(BasicConstant.ZERO);
                            if(Objects.nonNull(payPlanObj)) {
                                invoiceMap.put(payPlanObj.getLong(BasicConstant.ID), amountObj.getDouble(InvoiceConstant.INVOICE_AMOUNT));
                            }
                        }else if (CollectionsUtil.isNotEmpty(amountObj.getJSONArray(InvoiceConstant.PAYSHEET))) {
                            JSONObject paySheetObj = amountObj.getJSONArray(InvoiceConstant.PAYSHEET).getJSONObject(BasicConstant.ZERO);
                            if(Objects.nonNull(paySheetObj)) {
                                invoiceMap.put(paySheetObj.getLong(BasicConstant.ID), amountObj.getDouble(InvoiceConstant.INVOICE_AMOUNT));
                            }
                        }else if(CollectionsUtil.isNotEmpty(amountObj.getJSONArray(InvoiceConstant.PURCHASE))){
                            JSONObject purchaseObj = amountObj.getJSONArray(InvoiceConstant.PURCHASE).getJSONObject(BasicConstant.ZERO);
                            if(Objects.nonNull(purchaseObj)) {
                                invoiceMap.put(purchaseObj.getLong(BasicConstant.ID), amountObj.getDouble(InvoiceConstant.INVOICE_AMOUNT));
                            }
                        }
                    }
                }
            }
        }
        double sumAmount = 0D;
        if(CollectionsUtil.isNotEmpty(amountDetail)){
            for (int i = 0; i < amountDetail.size(); i++) {
                JSONObject amountObj = amountDetail.getJSONObject(i);
                if(Objects.nonNull(amountObj)){
                    if (CollectionsUtil.isNotEmpty(amountObj.getJSONArray(InvoiceConstant.PAYPLAN))) {
                        JSONObject payPlanObj = amountObj.getJSONArray(InvoiceConstant.PAYPLAN).getJSONObject(BasicConstant.ZERO);
                        if(Objects.nonNull(payPlanObj)) {
                            Long payPlanId = payPlanObj.getLong(BasicConstant.ID);
                            amountObj.put(InvoiceConstant.INVOICE_AMOUNT, invoiceMap.getOrDefault(payPlanId, 0D));
                        }
                    }else if (CollectionsUtil.isNotEmpty(amountObj.getJSONArray(InvoiceConstant.PAYSHEET))) {
                        JSONObject paySheetObj = amountObj.getJSONArray(InvoiceConstant.PAYSHEET).getJSONObject(BasicConstant.ZERO);
                        if(Objects.nonNull(paySheetObj)) {
                            Long paySheetId = paySheetObj.getLong(BasicConstant.ID);
                            amountObj.put(InvoiceConstant.INVOICE_AMOUNT, invoiceMap.getOrDefault(paySheetId, 0D));
                        }
                    }else if(CollectionsUtil.isNotEmpty(amountObj.getJSONArray(InvoiceConstant.PURCHASE))){
                        JSONObject purchaseObj = amountObj.getJSONArray(InvoiceConstant.PURCHASE).getJSONObject(BasicConstant.ZERO);
                        if(Objects.nonNull(purchaseObj)){
                            Long purchaseId = purchaseObj.getLong(BasicConstant.ID);
                            amountObj.put(InvoiceConstant.INVOICE_AMOUNT,invoiceMap.getOrDefault(purchaseId,0D));
                        }
                    }
                }
                if (Objects.equals(BasicConstant.ONE, purchaseInvoiceAmountDetailGetDTO.getFormRed()) || Objects.equals(BasicConstant.ONE, purchaseInvoiceAmountDetailGetDTO.getIsRed())) {
                    //红冲新增或者红冲编辑
                    sumAmount = Arith.add(amountObj.getDouble(InvoiceConstant.INVOICE_AMOUNT),sumAmount);
                }else {
                    sumAmount = Arith.add(amountObj.getDouble(InvoiceConstant.MAX_INVOICE_AMOUNT),sumAmount);
                }

            }
            //兼容审批内sumAmount=0的情况，如果为0则读取父发票的发票金额
            if (Objects.equals(sumAmount, 0D)) {
                sumAmount = data.getDoubleValue(PurchaseInvoiceEnum.TOTAL_MONEY.getAttr());
            }
            for (int i = 0; i < amountDetail.size(); i++) {
                JSONObject amountObj = amountDetail.getJSONObject(i);
                amountObj.put(InvoiceConstant.SUM_AMOUNT,sumAmount);
            }
        }
        return amountDetail;
    }
}
